import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { SharedModule } from '../../shared/shared.module';
import { PagedResultDto } from '@abp/ng.core';
import { ActivatedRoute, RouterModule } from '@angular/router';

interface ChuRuKuLiuShuiDto {
  id: number;
  serialNumber: number;
  chuRuKuDanHao?: string;
  chuRuKuRiQi?: string;
  yeWuLeiXing?: string;
  chuRuKuLeiXing?: string;
  cangKuMingCheng?: string;
  ruKuShuLiang?: number;
  chuKuShuLiang?: number;
  ruKuJinE?: number;
  chuKuJinE?: number;
  jingBanRen?: string;
  zhiDanRen?: string;
  suoZaiPianQu?: string;
  youXiaoQi?: string;
  
  ioOrderCode?: string;
  iodate?: string;
  businessType?: string;
  ioType?: string;
  warehouseName?: string;
  inQuantity?: number;
  outQuantity?: number;
  inAmount?: number;
  outAmount?: number;
  operator?: string;
  creator?: string;
  department?: string;
  createTime?: string;
}

interface ChuRuKuLiuShuiQueryParams {
  ChuRuKuDanHao?: string;
  CangKuMingCheng?: string;
  YeWuLeiXing?: string;
  ChuRuKuLeiXing?: string;
  ChuRuKuRiQiStart?: string;
  ChuRuKuRiQiEnd?: string;
  SkipCount: number;
  MaxResultCount: number;
  Sorting?: string;
}

@Component({
  selector: 'app-chu-ru-ku-liu-shui',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    SharedModule,
    RouterModule
  ],
  templateUrl: './chu-ru-ku-liu-shui.component.html',
  styleUrls: ['./chu-ru-ku-liu-shui.component.scss']
})
export class ChuRuKuLiuShuiComponent implements OnInit {
  // 查询参数
  queryParams: ChuRuKuLiuShuiQueryParams = {
    SkipCount: 0,
    MaxResultCount: 10
  };

  // 日期范围
  dateRange: { start: string, end: string } = {
    start: '',
    end: ''
  };

  // 页码和页大小设置
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  
  // 数据列表
  dataList: ChuRuKuLiuShuiDto[] = [];
  allDataList: ChuRuKuLiuShuiDto[] = []; // 用于存储所有数据，用于提取下拉选项
  
  // 选中的行
  selectedRows: number[] = [];
  
  // 加载状态
  loading = false;
  apiError = false;
  errorMessage = '';
  
  // 统计数据
  statistics = {
    ruKuShuLiang: 0,
    ruKuJinE: 0,
    chuKuShuLiang: 0,
    chuKuJinE: 0
  };
  
  // 下拉选项 - 从表格数据中提取
  yeWuLeiXingOptions: string[] = [];
  chuRuKuLeiXingOptions: string[] = [];
  cangKuOptions: string[] = [];
  
  // 货品信息
  goodsInfo = {
    code: 'HPDH2025070620473267',
    name: '商品类型',
    specification: '规格型号',
    model: '20*50*60',
    unit: '箱'
  };

  constructor(
    private http: HttpClient,
    public route: ActivatedRoute
  ) {
    // 初始化日期范围为空
    this.dateRange = {
      start: '',
      end: ''
    };
  }

  ngOnInit(): void {
    console.log('ChuRuKuLiuShuiComponent初始化');
    
    // 从路由参数中获取货品编码
    this.route.queryParams.subscribe(params => {
      console.log('接收到路由参数:', params);
      
      if (params['goodsCode']) {
        console.log('获取到商品编码:', params['goodsCode']);
        this.goodsInfo.code = params['goodsCode'];
        
        // 这里可以根据商品编码查询商品详情
        // 暂时使用模拟数据
        this.goodsInfo = {
          code: params['goodsCode'],
          name: params['goodsName'] || '商品类型-' + params['goodsCode'].substring(0, 4),
          specification: '规格型号',
          model: '20*50*60',
          unit: '箱'
        };
        
        console.log('设置商品信息:', this.goodsInfo);
      } else {
        console.warn('未获取到商品编码参数');
      }
      
      // 初始化默认下拉选项
      this.initDefaultOptions();
      
      // 立即加载数据
      this.loadData();
    });
  }

  // 初始化默认下拉选项
  initDefaultOptions(): void {
    // 初始化为空数组，稍后将从数据中提取
    this.yeWuLeiXingOptions = [];
    this.chuRuKuLeiXingOptions = [];
    this.cangKuOptions = [];
    
    // 调用后端API获取所有可能的下拉选项
    this.fetchAllOptionsFromServer();
  }

  // 从服务器获取所有可能的下拉选项
  fetchAllOptionsFromServer(): void {
    console.log('尝试从服务器获取所有下拉选项...');
    
    // 创建一个包含大量数据的请求，以获取更多数据用于提取选项
    const apiUrl = 'https://localhost:44359/api/app/chu-ru-ku-liu-shui';
    let params = new HttpParams()
      .set('MaxResultCount', '1000') // 获取尽可能多的数据
      .set('SkipCount', '0');
      
    // 添加商品编码参数，如果有的话
    if (this.goodsInfo && this.goodsInfo.code) {
      params = params.set('GoodsCode', this.goodsInfo.code);
    }
    
    this.http.get<PagedResultDto<ChuRuKuLiuShuiDto>>(apiUrl, { params })
      .subscribe({
        next: (response) => {
          if (response && response.items && response.items.length > 0) {
            console.log('成功获取选项数据，记录数:', response.items.length);
            // 更新全部数据列表
            this.updateAllDataList(response.items);
            // 从数据中提取下拉选项
            this.extractOptionsFromData();
          } else {
            console.warn('获取选项数据为空，将使用模拟数据');
            // 创建模拟数据并提取选项
            this.createMockOptionsData();
          }
        },
        error: (error) => {
          console.error('获取选项数据失败:', error);
          // 创建模拟数据并提取选项
          this.createMockOptionsData();
        }
      });
  }
  
  // 创建模拟数据用于提取选项
  createMockOptionsData(): void {
    console.log('创建模拟数据用于提取下拉选项...');
    
    // 生成足够多样化的模拟数据以提供丰富的选项
    const mockItems: ChuRuKuLiuShuiDto[] = [];
    
    // 模拟数据中的仓库名称
    const warehouseNames = ['主仓库', '办公仓库', '食品仓库', 'C区-03', 'B区-02', 'A区-01', '电子产品仓库', '服装仓库'];
    
    // 模拟数据中的业务类型
    const businessTypes = ['入库', '出库', '调拨', '盘点'];
    
    // 模拟数据中的出入库类型
    const ioTypes = ['进货入库', '退货入库', '调拨入库', '盘盈入库', '销售出库', '退货出库', '调拨出库', '盘亏出库'];
    
    // 生成30条模拟数据以确保覆盖各种情况
    for (let i = 1; i <= 30; i++) {
      const isInbound = i % 2 === 0; // 偶数为入库，奇数为出库
      const businessTypeIndex = i % businessTypes.length;
      const ioTypeIndex = isInbound ? (i % 4) : 4 + (i % 4); // 前4个为入库类型，后4个为出库类型
      
      const mockItem: ChuRuKuLiuShuiDto = {
        id: i,
        serialNumber: i,
        chuRuKuDanHao: `CRK${String(20250700 + i).padStart(8, '0')}`,
        chuRuKuRiQi: this.formatDateForMockData(i),
        yeWuLeiXing: businessTypes[businessTypeIndex],
        chuRuKuLeiXing: ioTypes[ioTypeIndex % ioTypes.length],
        cangKuMingCheng: warehouseNames[i % warehouseNames.length],
        ruKuShuLiang: isInbound ? 100 + i * 10 : 0,
        chuKuShuLiang: !isInbound ? 50 + i * 5 : 0,
        ruKuJinE: isInbound ? (100 + i * 10) * 25 : 0,
        chuKuJinE: !isInbound ? (50 + i * 5) * 35 : 0,
        jingBanRen: `操作员${i % 5 + 1}`,
        zhiDanRen: `制单人${i % 3 + 1}`,
        suoZaiPianQu: `区域${String.fromCharCode(65 + i % 5)}`,
        youXiaoQi: this.formatDateForMockData(i + 30)
      };
      
      mockItems.push(mockItem);
    }
    
    // 更新全部数据列表
    this.updateAllDataList(mockItems);
    
    // 从数据中提取下拉选项
    this.extractOptionsFromData();
  }

  // 从数据中提取下拉选项
  extractOptionsFromData(): void {
    // 仓库名称选项（去重）
    const warehouseSet = new Set<string>();
    this.allDataList.forEach(item => {
      const warehouseName = item.cangKuMingCheng || item.warehouseName;
      if (warehouseName && warehouseName.trim() !== '') warehouseSet.add(warehouseName);
    });
    this.cangKuOptions = Array.from(warehouseSet).sort();
    
    // 业务类型选项（去重）
    const businessTypeSet = new Set<string>();
    this.allDataList.forEach(item => {
      const businessType = item.yeWuLeiXing || item.businessType;
      if (businessType && businessType.trim() !== '') businessTypeSet.add(businessType);
    });
    this.yeWuLeiXingOptions = Array.from(businessTypeSet).sort();
    
    // 出入库类型选项（去重）
    const ioTypeSet = new Set<string>();
    this.allDataList.forEach(item => {
      const ioType = item.chuRuKuLeiXing || item.ioType;
      if (ioType && ioType.trim() !== '') ioTypeSet.add(ioType);
    });
    this.chuRuKuLeiXingOptions = Array.from(ioTypeSet).sort();
    
    console.log('从数据中提取的仓库选项:', this.cangKuOptions);
    console.log('从数据中提取的业务类型选项:', this.yeWuLeiXingOptions);
    console.log('从数据中提取的出入库类型选项:', this.chuRuKuLeiXingOptions);
    
    // 如果选项为空，添加一些默认选项
    if (this.cangKuOptions.length === 0) {
      this.cangKuOptions = ['主仓库', '办公仓库', '食品仓库'];
      console.warn('未能从数据中提取仓库选项，使用默认值');
    }
    
    if (this.yeWuLeiXingOptions.length === 0) {
      this.yeWuLeiXingOptions = ['入库', '出库'];
      console.warn('未能从数据中提取业务类型选项，使用默认值');
    }
    
    if (this.chuRuKuLeiXingOptions.length === 0) {
      this.chuRuKuLeiXingOptions = ['进货入库', '退货入库', '调拨入库', '销售出库', '退货出库', '调拨出库'];
      console.warn('未能从数据中提取出入库类型选项，使用默认值');
    }
  }

  // 处理日期范围变化
  onDateRangeChange(): void {
    // 更新查询参数中的日期
    this.queryParams.ChuRuKuRiQiStart = this.dateRange.start || '';
    this.queryParams.ChuRuKuRiQiEnd = this.dateRange.end || '';
    
    console.log('日期范围已更新:', this.dateRange);
    console.log('查询参数已更新:', this.queryParams);
  }

  // 加载数据
  loadData(): void {
    console.log('开始加载出入库流水数据');
    this.loading = true;
    this.apiError = false;
    
    this.queryParams.SkipCount = (this.pageIndex - 1) * this.pageSize;
    this.queryParams.MaxResultCount = this.pageSize;
    
    // 确保日期参数从dateRange获取最新值
    this.queryParams.ChuRuKuRiQiStart = this.dateRange.start || '';
    this.queryParams.ChuRuKuRiQiEnd = this.dateRange.end || '';
    
    const apiUrl = 'https://localhost:44359/api/app/chu-ru-ku-liu-shui';
    
    // 创建HttpParams对象
    let params = new HttpParams();
    
    // 添加商品编码参数
    if (this.goodsInfo && this.goodsInfo.code) {
      params = params.set('GoodsCode', this.goodsInfo.code);
      console.log('添加商品编码参数:', this.goodsInfo.code);
    } else {
      console.warn('没有商品编码参数!');
    }
    
    // 添加查询参数
    Object.keys(this.queryParams).forEach(key => {
      const value = this.queryParams[key as keyof ChuRuKuLiuShuiQueryParams];
      if (value !== undefined && value !== null && value !== '') {
        params = params.set(key, String(value));
      }
    });
    
    console.log('发送请求参数:', params.toString());
    console.log('完整API URL:', apiUrl + '?' + params.toString());
    
    this.http.get<PagedResultDto<ChuRuKuLiuShuiDto>>(apiUrl, { params })
      .subscribe({
        next: (response) => {
          console.log('API返回数据:', response);
          if (response && response.items) {
            console.log('API返回数据条数:', response.items.length);
            this.dataList = response.items;
            this.total = response.totalCount;
            
            // 更新全部数据列表
            this.updateAllDataList(response.items);
            
            // 从数据中提取下拉选项
            this.extractOptionsFromData();
            
            this.calculateStatistics();
          } else {
            console.warn('API返回数据格式不正确:', response);
            // 使用模拟数据
            this.mockData();
          }
          this.loading = false;
        },
        error: (error: HttpErrorResponse) => {
          console.error('获取出入库流水数据失败:', error);
          this.loading = false;
          this.apiError = true;
          
          if (error.status === 0) {
            this.errorMessage = '网络错误或CORS问题，请检查网络连接和后端CORS配置';
            console.error('可能是CORS问题或网络连接问题');
          } else {
            this.errorMessage = `获取数据失败: ${error.status} ${error.statusText}`;
            if (error.error && error.error.error) {
              this.errorMessage += ` - ${error.error.error.message || '未知错误'}`;
              console.error('API错误详情:', error.error.error);
            }
          }
          
          // 使用模拟数据
          this.mockData();
        }
      });
  }
  
  // 更新全部数据列表
  updateAllDataList(newData: ChuRuKuLiuShuiDto[]): void {
    // 合并新数据到全部数据列表，避免重复
    newData.forEach(item => {
      const exists = this.allDataList.some(existingItem => existingItem.id === item.id);
      if (!exists) {
        this.allDataList.push(item);
      }
    });
  }
  
  // 模拟数据（当API返回错误时使用）
  mockData(): void {
    console.log('使用模拟数据，当前货品编码:', this.goodsInfo.code);
    console.log('当前出入库单号查询参数:', this.queryParams.ChuRuKuDanHao);
    console.log('路由参数中的批次号:', this.route.snapshot.queryParams['batchNumber']);
    
    // 生成10条模拟数据
    const mockItems: ChuRuKuLiuShuiDto[] = [];
    
    // 模拟数据中的仓库名称
    const warehouseNames = ['主仓库', '办公仓库', '食品仓库', 'C区-03', 'B区-02', 'A区-01'];
    
    // 模拟数据中的业务类型
    const businessTypes = ['入库', '出库'];
    
    // 模拟数据中的出入库类型
    const ioTypes = ['进货入库', '退货入库', '调拨入库', '销售出库', '退货出库', '调拨出库'];
    
    // 生成模拟数据
    for (let i = 1; i <= 10; i++) {
      const isInbound = i % 2 === 0; // 偶数为入库，奇数为出库
      const businessType = businessTypes[isInbound ? 0 : 1];
      const ioType = ioTypes[isInbound ? (i % 3) : 3 + (i % 3)];
      
      const mockItem: ChuRuKuLiuShuiDto = {
        id: i,
        serialNumber: i,
        chuRuKuDanHao: `CRK${this.goodsInfo.code.slice(-6)}${String(i).padStart(3, '0')}`,
        chuRuKuRiQi: this.formatDateForMockData(i),
        yeWuLeiXing: businessType,
        chuRuKuLeiXing: ioType,
        cangKuMingCheng: warehouseNames[i % warehouseNames.length],
        ruKuShuLiang: isInbound ? 100 + i * 10 : 0,
        chuKuShuLiang: !isInbound ? 50 + i * 5 : 0,
        ruKuJinE: isInbound ? (100 + i * 10) * 25 : 0,
        chuKuJinE: !isInbound ? (50 + i * 5) * 35 : 0,
        jingBanRen: `操作员${i % 5 + 1}`,
        zhiDanRen: `制单人${i % 3 + 1}`,
        suoZaiPianQu: `区域${String.fromCharCode(65 + i % 5)}`,
        youXiaoQi: this.formatDateForMockData(i + 30)
      };
      
      mockItems.push(mockItem);
    }
    
    // 应用日期过滤
    let filteredItems = [...mockItems];
    
    if (this.dateRange.start || this.dateRange.end) {
      const startDate = this.dateRange.start ? new Date(this.dateRange.start) : null;
      const endDate = this.dateRange.end ? new Date(this.dateRange.end) : null;
      
      if (startDate) startDate.setHours(0, 0, 0, 0);
      if (endDate) endDate.setHours(23, 59, 59, 999);
      
      filteredItems = filteredItems.filter(item => {
        if (!item.chuRuKuRiQi) return true;
        
        const itemDate = new Date(item.chuRuKuRiQi);
        let matchesFilter = true;
        
        if (startDate && itemDate < startDate) {
          matchesFilter = false;
        }
        
        if (endDate && itemDate > endDate) {
          matchesFilter = false;
        }
        
        return matchesFilter;
      });
    }
    
    // 应用其他过滤条件
    if (this.queryParams.CangKuMingCheng) {
      filteredItems = filteredItems.filter(item => 
        item.cangKuMingCheng === this.queryParams.CangKuMingCheng
      );
    }
    
    if (this.queryParams.YeWuLeiXing) {
      filteredItems = filteredItems.filter(item => 
        item.yeWuLeiXing === this.queryParams.YeWuLeiXing
      );
    }
    
    if (this.queryParams.ChuRuKuLeiXing) {
      filteredItems = filteredItems.filter(item => 
        item.chuRuKuLeiXing === this.queryParams.ChuRuKuLeiXing
      );
    }
    
    this.dataList = filteredItems;
    this.total = filteredItems.length;
    
    // 更新全部数据列表
    this.updateAllDataList(mockItems);
    
    // 从数据中提取下拉选项
    this.extractOptionsFromData();
    
    // 计算统计数据
    this.calculateStatistics();
  }
  
  // 格式化日期为指定天数后的日期
  formatDateForMockData(daysFromNow: number): string {
    const date = new Date();
    date.setDate(date.getDate() - daysFromNow);
    return this.formatDate(date);
  }
  
  // 格式化日期为YYYY-MM-DD格式
  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  // 计算统计数据
  calculateStatistics(): void {
    this.statistics = {
      ruKuShuLiang: 0,
      ruKuJinE: 0,
      chuKuShuLiang: 0,
      chuKuJinE: 0
    };
    
    this.dataList.forEach(item => {
      this.statistics.ruKuShuLiang += (item.ruKuShuLiang || item.inQuantity || 0);
      this.statistics.ruKuJinE += (item.ruKuJinE || item.inAmount || 0);
      this.statistics.chuKuShuLiang += (item.chuKuShuLiang || item.outQuantity || 0);
      this.statistics.chuKuJinE += (item.chuKuJinE || item.outAmount || 0);
    });
  }
  
  // 重置筛选条件
  reset(): void {
    // 重置日期范围
    this.dateRange = {
      start: '',
      end: ''
    };
    
    // 重置查询参数
    this.queryParams = {
      SkipCount: 0,
      MaxResultCount: this.pageSize,
      Sorting: '',
      ChuRuKuRiQiStart: '',
      ChuRuKuRiQiEnd: ''
    };
    
    // 重置页码
    this.pageIndex = 1;
    
    // 重新加载数据
    this.loadData();
  }
  
  // 搜索
  search(): void {
    console.log('执行搜索...');
    
    // 更新查询参数中的日期
    this.queryParams.ChuRuKuRiQiStart = this.dateRange.start || '';
    this.queryParams.ChuRuKuRiQiEnd = this.dateRange.end || '';
    
    // 重置页码
    this.pageIndex = 1;
    
    // 加载数据
    this.loadData();
  }
  
  // 页码变更
  pageIndexChange(index: number): void {
    this.pageIndex = index;
    this.loadData();
  }
  
  // 页大小变更
  pageSizeChange(size: number): void {
    this.pageSize = Number(size);
    this.pageIndex = 1;
    this.loadData();
  }
  
  // 选择行
  toggleSelection(id: number): void {
    const index = this.selectedRows.indexOf(id);
    if (index === -1) {
      this.selectedRows.push(id);
    } else {
      this.selectedRows.splice(index, 1);
    }
  }
  
  // 导出
  exportData(): void {
    console.log('导出数据');
    alert('导出功能正在开发中');
  }
  
  // 刷新
  refresh(): void {
    this.loadData();
  }
  
  // 清空出入库单号
  clearBatchNumber(): void {
    console.log('手动清空出入库单号');
    this.queryParams.ChuRuKuDanHao = undefined;
    // 重新加载数据
    this.loadData();
  }
} 